package com.aloha.springframework.core.io;

import cn.hutool.core.lang.Assert;
import com.aloha.springframework.utils.ClassUtils;

import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;

/**
 * @author DaiZhiHeng
 * @description 在类路径下的资源
 * @date 2023/6/27 20:46
 */
public class ClassPathResource implements Resource {

    /**
     * 资源的路径
     */
    private final String path;

    /**
     * 用于加载资源的加载器
     */
    private final ClassLoader classLoader;

    public ClassPathResource(String path) {
        this(path, null);
    }

    public ClassPathResource(String path, ClassLoader classLoader) {
        Assert.notNull(path, "类路径不能为空");
        this.path = path;
        this.classLoader = classLoader == null ? ClassUtils.getDefaultClassLoader() : classLoader;
    }

    @Override
    public InputStream getInputStream() throws IOException {
        InputStream is = classLoader.getResourceAsStream(path);
        if (is == null) throw new FileNotFoundException(path + " 不存在");
        return is;
    }
}
